<template>
    <div class="box-content">
        <div class="navigation">用户管理/用户列表</div>
        <!--搜索-->
        <div class="mt-3">
            <div>
                <el-input type="text" style="width: 200px;"  :clearable="true" class=" mrt-10" v-model="search.inputName" placeholder="输入关键字用户名/手机号"></el-input>
                <el-select v-model="search.roleStatus" :clearable="true" style="width: 110px;" class=" mrt-10" placeholder="角色状态">
                    <el-option label="暂停" value="0"></el-option>
                    <el-option label="正常" value="1"></el-option>
                </el-select>
                <el-button type="primary" class=" mrt-10" @click="onSearch">查询</el-button>
                <el-button type="primary" @click="openShanHu">新增</el-button>
            </div>
        </div>
        <!--表格-->
        <div class="mt-3">
            <el-table
                    :data="userData"
                    v-loading="loading"
                    align="center"
                    :element-loading-text="loadText"
                    :header-cell-style="tableHeaderColor"
                    stripe
                    style="width: 100%">
                <el-table-column
                        prop="id"
                        align="center"
                        label="编号"
                        width="100"
                >
                </el-table-column>
                <el-table-column
                        prop="name"
                        align="center"
                        label="昵称"
                >
                </el-table-column>
                <el-table-column
                        prop="phone"
                        align="center"
                        label="手机号"
                        width="150"
                >
                </el-table-column>
                <el-table-column
                        align="center"
                        label="账户状态"
                >
                    <template slot-scope="scope">
                        <el-switch
                                v-model="scope.row.status"
                                :active-value="1"
                                :inactive-value="0"
                                @change=changeStatus(scope.row)></el-switch>
                    </template>
                </el-table-column>
                <el-table-column
                        label="创建日期"
                        align="center"
                        width="100">
                    <template slot-scope="scope">
                        <div align="center">{{scope.row['created_at']?scope.row['created_at'].slice(0, 11):'无'}}</div>
                        <div align="center">{{scope.row['created_at']?scope.row['created_at'].slice(11 ):'无'}}</div>
                    </template>
                </el-table-column>
                <el-table-column
                        label="状态/操作"
                        align="center"
                        fixed="right"
                        width="220"
                >
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                type="primary"
                                @click="handleEdit(scope.row)">编辑
                        </el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                @click="handleDelete(scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="mt-3 float-right">
                <el-pagination
                        background
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="pageInfo.current_page"
                        :page-size="pageInfo.per_page"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="pageInfo.total">
                </el-pagination>
            </div>
        </div>
        <!--新增对话框-->
        <el-dialog :title="dialog.title"
                   :visible.sync="dialogFormVisible"
                   :close-on-click-modal="false"
                   width="600px">
            <el-form :model="form" :rules="rules" ref="form" label-width="110px" v-loading="loadingDialig">
                <el-form-item label="角色" prop="user">
                    <el-select v-model="form.user" multiple placeholder="请选择角色" style="width: 450px;">
                        <el-option
                                v-for="item in listData"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号" prop="phone" v-if="!dialog.isEdit">
                    <el-input  v-model="form.phone" placeholder="请输入电话号码" style="width: 450px;"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password" v-if="!dialog.isEdit">
                    <el-input v-model="form.password" placeholder="请输入密码" style="width: 450px;"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password_edit" v-if="dialog.isEdit" style="position: relative">
                    <el-input v-model="form.password_edit" placeholder="请输入密码" style="width: 450px;"></el-input>
                    <div style="position: absolute;top: 30px;color: red;font-size: 12px">编辑修改时未传密码则保持原密码不变！</div>
                </el-form-item>
                <el-form-item label="昵称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入昵称" style="width: 450px;"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" v-if="!dialog.isEdit" :loading="loadingCreate" @click="submitCostomer('form')">{{loadingCreate?'创建中':'点击创建'}}</el-button>
                <el-button type="primary" v-if="dialog.isEdit"  :loading="loadingCreate" @click="submitCostomer('form')">{{loadingCreate?'修改中':'点击修改'}}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import axios from 'axios';
    import UserSearch from '../../components/UserInfo.vue'
    export default {
        name: "userList",
        components:{
            UserSearch
        },
        data() {
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    var r = /^[^\u4e00-\u9fa5]+$/
                    if(!r.test(value)){
                        callback(new Error('密码不能为中文!'));
                    }
                    if (value.length < 6 ) {
                        callback(new Error('密码长度在 6 到 18 个字符!'));
                    }
                    callback();
                }
            };
            var validateName = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入用户名'));
                } else {
                    if (value.length > 10) {
                        callback(new Error('昵称小于10个字符'));
                    }
                    callback();
                }
            };
            var phoneValid = (rule, value, callback) => {
                let phoneReg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
                if (!value) {
                    callback(new Error('请输入手机号码'))
                }
                if (!phoneReg.test(value)) {
                    callback(new Error('请输入正确的手机号码'))
                }
                callback()
            };
            return {
                editId: null,
                userInfo: {},
                pageInfo: {
                    per_page: 10,
                    total: 0,
                    current_page: 1
                },
                loadText: '数据加载中',
                userData: [],
                searchStr:'',
                search: {
                    roleStatus:'',
                    inputName:''
                },
                baseId: null,
                loading: false,
                loadingDialig: false,
                loadingCreate: false,
                dialogFormVisible: false,
                listData:[],
                form: {
                    name:'',
                    phone:'',
                    password:'',
                    user:[],
                    password_edit:''
                },
                dialog: {
                    title: '',
                    isEdit: false
                },
                rules: {
                    phone: [
                        { validator: phoneValid, trigger: 'change' }
                    ],
                    name: [
                        { validator: validateName, trigger: 'change' }
                    ],
                    password: [
                        { validator: validatePass, trigger: 'change' }
                    ],
                    user: [
                        {required: true, message: '请选择角色', trigger: 'change'}
                    ]
                }

            }
        },
        watch: {
            dialogFormVisible:function (val) {
                if (!val) {
                    Object.keys(this.form).forEach(key => this.form[key] = '');
                    this.$refs['form'].resetFields();
                    this.editId = null;
                }
            }
        },

        created() {
            this.getUserList();
            this.getCustomerList();
        },
        methods: {
            getUserList() {
                this.$http.get('api/admin/auth/role')
                    .then((result) => {
                        this.listData = result.data;
                    })
                    .catch((err) => {
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            changeName(val) {
                this.search.inputName = val;
            },
            openShanHu(){
                this.dialog.title = '注册账户';
                this.dialog.isEdit = false;
                this.dialogFormVisible = true;
            },
            getCustomerList() {
                this.loading = true;
                this.$http.get('api/admin/common/user' + this.searchStr, {
                    params: {
                        pageSize: this.pageInfo.per_page,
                        page: this.pageInfo.current_page
                    }
                })
                    .then((result) => {
                        this.userData = result.data;
                        this.pageInfo.total = result.meta.total;
                        this.loading = false;
                    })
                    .catch((err) => {
                        this.loading = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            onSearch() {
                this.searchStr ="";
                if (this.search.inputName) {
                    this.addConStr();
                    this.searchStr += `name|phone$=%${this.search.inputName}%`;
                }
                if (this.search.roleStatus) {
                    this.addConStr();
                    this.searchStr += `status=${this.search.roleStatus}`;
                }
                this.pageInfo.current_page = 1;
                this.getCustomerList();
            },
            addConStr() {
                if (this.searchStr.length > 0) {
                    this.searchStr += '&';
                } else {
                    this.searchStr += '?';
                }
            },
            submitCostomer(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.creatShanHu();
                    } else {
                        return false;
                    }
                });
            },
            creatShanHu(){
                this.loadingCreate = true;
                let params;

                if (this.dialog.isEdit) {
                    if (this.form.password_edit) {
                        params={
                            name: this.form.name,
                            roles: this.form.user,
                            password: this.form.password_edit
                        };
                    } else {
                        params={
                            name: this.form.name,
                            roles: this.form.user
                        };
                    }
                    this.$http.put('api/admin/common/user/' + this.baseId, params)
                        .then((result) => {
                            this.$message({
                                type: 'success',
                                message: '修改成功!',
                                during:1000
                            });
                            this.dialogFormVisible = false;
                            this.loadingCreate = false;
                            this.getCustomerList();
                        })
                        .catch((err) => {
                            this.loadingCreate = false;
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                } else {
                    params={
                        name: this.form.name,
                        phone: this.form.phone,
                        roles: this.form.user,
                        password: this.form.password
                    };

                    this.$http.post('api/admin/user/session/register', params)
                        .then((result) => {
                            if (result.code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: '注册成功!',
                                    during:1000
                                });
                                this.dialogFormVisible = false;
                                this.getCustomerList();
                            }
                            this.loadingCreate = false;
                        })
                        .catch((err) => {
                            this.loadingCreate = false;
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                }

            },
            handleEdit(val) {
                this.baseId = val.id;
                this.dialog.title = '编辑账户';
                this.dialog.isEdit = true;
                this.dialogFormVisible = true;
                this.loadingDialig = true;
                this.form.user = [];
                this.$http.get('api/admin/common/user/' + val.id)
                    .then((result) => {
                        // this.userData = result.data;
                        result.data.roles.forEach(item=>{
                            this.form.user.push(item.id)
                        })
                        this.editId = result.data.id;
                        this.form.name = result.data.name;
                        this.form.phone = result.data.phone;
                        this.loadingDialig = false;
                    })
                    .catch((err) => {
                        this.loadingDialig = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            handleDelete(val) {
                this.$confirm('此操作将永久删除账户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.delete('api/admin/common/user/' + val.id)
                        .then((result) => {
                            this.$message({
                                type: 'success',
                                message: '账号删除成功!',
                                during:1000
                            });
                            this.getCustomerList();
                        })
                        .catch((err) => {
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                }).catch(() => {
                });
            },
            changeStatus(val) {
                let params = {
                    status: val.status
                };
                this.$http.put('api/admin/common/user/' + val.id, params)
                    .then((result) => {
                        this.$message({
                            type: 'success',
                            message: result.msg,
                            during: 1000
                        });
                    })
                    .catch((err) => {
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            handleSizeChange(val) {
                this.pageInfo.current_page = 1;
                this.pageInfo.per_page = val;
                this.getCustomerList();
            },
            handleCurrentChange(val) {
                this.pageInfo.current_page = val;
                this.getCustomerList();
            },
            tableHeaderColor({row, column, rowIndex, columnIndex}) {
                if (rowIndex === 0) {
                    return 'background-color: #FAFAFA;color: #000;font-weight: 500;height:54px;font-size:14px'
                }
            }
        }
    }
</script>

<style lang="less" >
    .check-children{
        cursor: pointer;
    }
    .check-children:hover{
        color: #409EFF;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 100px;
        height: 100px;
        line-height: 100px;
        text-align: center;
    }
    .avatar {
        width: 100px;
        height: 100px;
        display: block;
    }
</style>